package connection

import (
	"os"
	"path/filepath"
	"text/template"

	"gitee.com/extrame/fb-runner/ca"
	"gitee.com/extrame/fb-runner/util"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

type GenerateReq struct {
	util.OrganizationWithBase
	UserName string
}

func Generate(channel, source, generatedBase, base, deployBase string, org *util.Organization, lang string, user ...*ca.User) error {

	t, err := template.New("ccp-template-" + lang + ".json").Funcs(template.FuncMap{
		"isLast": func(i int, peers map[string]*util.Peer) bool {
			return i == len(peers)-1
		},
	}).ParseFiles(filepath.Join(source, "ccp-template-"+lang+".json"))
	util.Mkdir(base)
	if err == nil {
		var f *os.File
		f, err = os.OpenFile(filepath.Join(base, "connection.json"), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
		if err == nil {
			var input = util.OrganizationWithBase{
				Base:         deployBase,
				RealBase:     generatedBase,
				Channel:      channel,
				Organization: *org,
			}
			err = t.Execute(f, &input)
			f.Close()

		}
	} else {
		return errors.Wrap(err, "解析json文件")
	}

	if err == nil {

		t, err = template.ParseFiles(filepath.Join(source, "ccp-template-"+lang+".yaml"))
		if err == nil {
			var f *os.File
			f, err = os.OpenFile(filepath.Join(base, "connection.yaml"), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
			if err == nil {
				var input = util.OrganizationWithBase{
					Base:         deployBase,
					Channel:      channel,
					RealBase:     generatedBase,
					Organization: *org,
				}
				err = t.Execute(f, &input)
				f.Close()
			}
		} else {
			return errors.Wrap(err, "解析yaml文件")
		}
	} else {
		return errors.Wrap(err, "生成json文件")
	}

	if err == nil {
		switch lang {
		case "java":
			t, err = template.ParseFiles(filepath.Join(source, "wallet-admin-id"))
			if err == nil {
				var f *os.File

				for _, u := range user {
					var fName = filepath.Join(base, "wallet", u.Name+".id")
					util.MkdirFor(fName)
					f, err = os.OpenFile(fName, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
					if err == nil {
						var input = GenerateReq{
							util.OrganizationWithBase{
								Base:         deployBase,
								Channel:      channel,
								RealBase:     base,
								Organization: *org,
							},
							u.GetTitle(),
						}
						err = t.Execute(f, &input)
						f.Close()
					}
				}
			}
		case "golang":
			logrus.Info("Golang请拷贝基础配置文件夹", generatedBase)
		}
	}

	return err
}
